let global_page = 1,
  global_limit = 5,
  goodUrl = '/goods';

function loadGoods(name) {
  name = name === 'undefined' ? '' : name;
  loadLayuiForm();
  $.get(goodUrl + '/findGoodsByPage', {page: global_page, limit: global_limit, name: name}, goods => {
    if (goods.data.length === 0 && global_page > 1) {
      global_page--;
      loadGoods();
    } else {
      loadGoodsTable(goods);
      loadGoodLayPage(goods);
    }
  });
}

function loadGoodsTable(goods) {
  layui.use(['table', 'layer', 'form'], () => {
    let table = layui.table,
      layer = layui.layer,
      form = layui.form;
    table.render({
      elem: '#good',
      data: goods.data,
      limit: global_limit,
      toolbar: '#good-toolbar',
      cols: [
        [
          {field: 'name', title: '名称'},
          {field: 'code', title: '编号'},
          {field: 'brand', title: '品牌'},
          {field: 'type', title: '种类'},
          {field: 'price', title: '单价'},
          {field: 'warehouse', title: '库存量/个'},
          {field: 'creater', title: '录入人'},
          {title: '操作', toolbar: '#good-tool'}
        ]
      ]
    });
    table.on('toolbar(good)', elem => {
      let event = elem.event;
      switch (event) {
        case 'add':
          $('input[name=creater]').val($('.layui-header .layui-nav-item a:eq(0)').text());
          $.get(goodUrl + '/findAllType', types => {
            let typeHtml = '';
            $.each(types, (i, v) => {
              typeHtml += '<option value="' + v.id + '">' + v.name + '</option>';
            });
            $('select[name=type]').html(typeHtml);
            form.render();
          });
          showLayout($('#add-good-layout'));
          break;
        case 'search':
          loadGoods($('#search').val());
          break;
      }
    });
    table.on('tool(good)', elem => {
      let event = elem.event,
        data = elem.data;
      switch (event) {
        case 'edit':
          $.get(goodUrl + '/findGoodsById/' + data.id, good => {
            let input = $('#edit-good-layout').find('input, textarea');
            $.each(input, (i) => {
              input.eq(i).val(good[input.eq(i).attr('name')]);
            });
            $('#edit-good-layout input[name=updater]').val($('.layui-header .layui-nav-item a:eq(0)').text());
            $.get(goodUrl + '/findAllType', types => {
              let typeHtml = '';
              $.each(types, (i, v) => {
                let check = good.type === v.id ? 'selected' : '';
                typeHtml += '<option value="' + v.id + '" ' + check + '>' + v.name + '</option>';
              });
              $('#edit-good-layout select[name=type]').html(typeHtml);
              form.render();
            });
          });
          showLayout($('#edit-good-layout'));
          break;
        case 'del':
          layer.confirm('确定删除该商品信息?', {
            btn: ['确定', '再想想']
          }, () => {
            $.post(goodUrl + '/delGoods/' + data.id, result => {
              result = result > 0 ? '成功' : '失败';
              layer.msg('该商品信息删除' + result + '!');
              hideLayout($('#edit-good-layout'));
              loadGoods();
            });
          });
          break;
        case 'out':
          if (data.warehouse === 0) {
            layer.msg('警告！库存不足！');
          } else {
            $('#out-warehouse-layout input[name=id]').val(data.id);
            $('#out-warehouse-layout input[name=updater]').val($('.layui-header .layui-nav-item a:eq(0)').text());
            showLayout($('#out-warehouse-layout'));
          }
          break;
      }
    });
  });
}

function loadGoodLayPage(goods) {
  layui.use('laypage', () => {
    layui.laypage.render({
      elem: 'good-page',
      curr: global_page,
      limit: global_limit,
      limits: [5, 10, 20, 50],
      count: goods.count,
      layout: ['count', 'prev', 'page', 'next', 'limit'],
      jump: function (obj, first) {
        if (!first) {
          global_page = obj.curr;
          global_limit = obj.limit;
          loadGoods();
        }
      }
    });
  })
}

function loadLayuiForm() {
  layui.use(['element', 'form', 'layer'], () => {
    let form = layui.form,
      layer = layui.layer;
    form.on('submit(add)', elem => {
      if (!regexDecimal(elem.field.price)) {
        layer.msg('价格必须为整数或小数!');
      } else {
        $.post(goodUrl + '/addGoods', elem.field, result => {
          result = result > 0 ? '成功' : '失败';
          layer.msg('商品信息录入' + result + '!');
          hideLayout($('#add-good-layout'));
          loadGoods();
        });
      }
    });
    form.on('submit(edit)', elem => {
      if (!regexDecimal(elem.field.purchase) || !regexDecimal(elem.field.selling)) {
        layer.msg('价格必须为整数或小数!');
      } else {
        $.post(goodUrl + '/updateGoods', elem.field, result => {
          result = result > 0 ? '成功' : '失败';
          layer.msg('商品信息修改' + result + '!');
          hideLayout($('#edit-good-layout'));
          loadGoods();
        });
      }
    });
    form.on('submit(out)', elem => {
      $.get(goodUrl + '/findGoodsById/' + elem.field.id, good => {
        if (elem.field.count > good.warehouse) {
          layer.msg('警告！库存不足！');
        } else {
          $.post('/warehouse/outWarehouse', elem.field, result => {
            result = result > 0 ? '成功' : '失败';
            layer.msg('商品出库' + result + '!');
            hideLayout($('#out-warehouse-layout'));
            loadGoods();
          });
        }
      });
    });
  });
}